package com.studyroom.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Random;
import java.util.ResourceBundle;

/**
 * @author wuhongbin
 * @createTime 2022年03月13日 16:10:00
 */
public class OSSClientUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(OSSClientUtils.class);

    public static ResourceBundle resourceBundle = ResourceBundle.getBundle("static/key");

    public static final String ENDPOINT = resourceBundle.getString("oss.endPoint");

    public static final String ACCESS_KEY_ID = resourceBundle.getString("oss.accessKeyId");

    public static final String ACCESS_KEY_SECRET = resourceBundle.getString("oss.accessKeySecret");

    public static final String BUCKET_NAME = resourceBundle.getString("oss.bucket");

    public static final String OSS_PREFIX = resourceBundle.getString("oss.prefix");



    /**
     * 图片文件上传OSS
     *
     * @param file   上传文件
     * @return 文件访问路径
     */
    public static String uploadFileNew(MultipartFile file, String fileName, String floder) {
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //如果不存在则创建存储空间
        if (!ossClient.doesBucketExist(BUCKET_NAME)) {
            ossClient.createBucket(BUCKET_NAME);
            LOGGER.info("创建存储空间:{}成功", BUCKET_NAME);
        }
        //创建文件路径
        String timingImageName = createTimingImageName();
        String fileUrl = timingImageName;
        try {
            //上传文件
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/png");

            ossClient.putObject(BUCKET_NAME, fileUrl, file.getInputStream(), objectMetadata);
            return timingImageName;
        } catch (IOException e) {
            LOGGER.error("获取文件流异常：" + e.getMessage(), e);
            return null;
        } finally {
            ossClient.shutdown();
        }
    }

    private static String createTimingImageName() {

        return OSS_PREFIX + System.currentTimeMillis()
                + MD5Utils.getMD5Format(String.valueOf(new Random().nextInt(10001)));
    }

}
